﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VoiceAI;
using VoiceAI.VoiceResponse;
using Windows.Foundation.Collections;
using Xiaowei.Diagnostics;
using Xiaowei.Helpers;
using Xiaowei.Players;
using Xiaowei.Players.XiaoweiPlayerLib;
using Xiaowei.Players.XiaoweiPlayerLib.QQFM;
using Xiaowei.Services;
using Xiaowei.Settings;
using XiaoweiVoiceAI;

namespace Xiaowei.ResponseHandlers
{
    public static class PlayControlResponseHandler
    {
        public static void Handle(IResponseData responseData)
        {
            if (responseData is IPlayControlResponseData playControlResponseData)
            {
                ViewModels.PlayControlBubbleViewModel playControlBubbleViewModel = new ViewModels.PlayControlBubbleViewModel();
                playControlResponseData.DataContext = playControlBubbleViewModel;
                playControlBubbleViewModel.ResponseText = playControlResponseData.ResponseText;
                IPlayer player = null;
                switch (playControlResponseData.PlayerType)
                {
                    case PlayerType.Music:
                        player = PlayerService.Instance.GetPlayerByType( PlayerService.PlayerType.Music);
                        break;
                    case PlayerType.Video:
                        if(/*SystemState.IsLocked*/false)
                        {
                            playControlResponseData.ResponseText = "对不起，锁屏下不支持此功能";
                            playControlResponseData.TTSUrl = XiaoweiAI.Instance.RequestTTS("对不起，锁屏下不支持此功能");
                            playControlBubbleViewModel.ResponseText = "对不起，锁屏下不支持此功能";
                            break;
                        }
                        player = PlayerService.Instance.GetPlayerByType(PlayerService.PlayerType.Video);
                        break;
                    case PlayerType.News:
                    case PlayerType.Radio:
                    case PlayerType.Weixintingshu:
                        player = PlayerService.Instance.GetPlayerByType(PlayerService.PlayerType.Radio);
                        break;
                    default:
                        break;
                }
                if (player != null)
                {
                    switch (playControlResponseData.PlayControlType)
                    {
                        case PlayControlType.Play:
                            player.Play();
                            break;
                        case PlayControlType.Stop:
                            player.Stop();
                            break;
                        case PlayControlType.Pause:
                            player.Pause();
                            break;
                        case PlayControlType.Prev:
                            player.Prev();
                            break;
                        case PlayControlType.Next:
                            player.Next();
                            break;
                        case PlayControlType.AddOffset:
                            if (playControlResponseData.ControlValue == null) break;
                            if (playControlResponseData.ControlValue > 0)
                            {
                                player.FastForward(playControlResponseData.ControlValue.Value);
                            }
                            else
                            {
                                player.FastRewind(-playControlResponseData.ControlValue.Value);
                            }
                            break;
                        case PlayControlType.SetOffsetTo:
                            if (playControlResponseData.ControlValue == null) break;
                            player.SeekTo(playControlResponseData.ControlValue.Value);
                            break;
                        case PlayControlType.PlayMode:
                            if (playControlResponseData.ControlValue == null) break;
                            switch ((VoiceAI.VoiceResponse.PlayMode)playControlResponseData.ControlValue)
                            {
                                case VoiceAI.VoiceResponse.PlayMode.SinglePlay:
                                    player.PlayBySingleLoop();
                                    break;
                                case VoiceAI.VoiceResponse.PlayMode.OrderPlay:
                                    player.PlayByOrder();
                                    break;
                                case VoiceAI.VoiceResponse.PlayMode.LoopPlay:
                                    player.PlayByListLoop();
                                    break;
                                case VoiceAI.VoiceResponse.PlayMode.RandomPlay:
                                    player.PlayByRandom();
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case PlayControlType.FullScreen:
                            ServiceFactory.TencentVideoService.SendVoiceText("全屏播放");
                            break;
                        case PlayControlType.PlayResource:
                            switch (playControlResponseData.PlayerType)
                            {
                                case PlayerType.Music:
                                    int state = LocalSettings.QQMusicInstallState;
                                    if (!player.IsInstalled)
                                    {
                                        if (state == 2)
                                        {
                                            LocalSettings.QQMusicInstallState = 0;
                                        }
                                    }
                                    else
                                    {
                                        if (state == 1)
                                        {
                                            _ = ServerApi.Instance.DownloadRecord(ServerApi.SupportedApp.QQMusic.GetHashCode(), XiaoweiAI.Instance.UserId, LocalSettings.DeviceName);
                                        }
                                        LocalSettings.QQMusicInstallState = 2;
                                    }
                                    if (!player.IsInstalled)
                                    {
                                        playControlResponseData.ResponseText = "你没有安装QQ音乐客户端，如果从此链接获取，你将可以直接用说来听音乐了。";
                                        playControlResponseData.TTSUrl = XiaoweiAI.Instance.RequestTTS(playControlResponseData.ResponseText);
                                        playControlBubbleViewModel.ShowNoMusicTip = true;
                                        playControlBubbleViewModel.ShowResponse = false;
                                        break;
                                    }

                                    if (playControlResponseData.PlayableResource is IMusicResource musicResource)
                                    {
                                        if (LocalSettings.FirstQQMusicCommand)
                                        {
                                            LocalSettings.FirstQQMusicCommand = false;
                                            playControlResponseData.TTSUrl = XiaoweiAI.Instance.RequestTTS(playControlResponseData.ResponseText + ",为了提高您的QQ音乐使用体验，请同时在QQ音乐PC客户端和腾讯小微微信小程序里绑定您的QQ音乐账号。");
                                            playControlBubbleViewModel.ShowFirstTimeUseMusicTip = true;
                                        }

                                        PlayerManager.Instance.CurrentPlayer = player;
                                        string id_0 = "";
                                        string songtype_0 = "";
                                        foreach (var item in musicResource.PlayIdList)
                                        {
                                            id_0 += item + "|";
                                            songtype_0 += "0|";
                                        }
                                        id_0 = id_0.TrimEnd('|');
                                        songtype_0 = songtype_0.TrimEnd('|');
                                        string args = "/playbysongid \"cmd_count==1&&id_0==" + id_0 + "&&songtype_0==" + songtype_0 + "&&info_0==0&&quality_0==0\"";
                                        player.Play(args);
                                    }


                                    break;
                                case PlayerType.Video:
                                    if (playControlResponseData.PlayableResource is IVideoResource videoResource)
                                    {
                                        PlayerManager.Instance.CurrentPlayer = player;
                                        string msg = "播放";
                                        try
                                        {
                                            if (!string.IsNullOrEmpty(videoResource.DirectorName))
                                            {
                                                msg += videoResource.DirectorName + "导演的";
                                            }
                                            if (!string.IsNullOrEmpty(videoResource.ActorName))
                                            {
                                                msg += videoResource.ActorName + "主演的";
                                            }
                                            if (!string.IsNullOrEmpty(videoResource.Year))
                                            {
                                                msg += videoResource.Year + "的";
                                            }
                                            msg += videoResource.VideoTag + videoResource.VideoChannel + videoResource.PlayName;
                                            if (!string.IsNullOrEmpty(videoResource.Season))
                                            {
                                                msg += "第" + videoResource.Season + "季";
                                            }
                                            if (!string.IsNullOrEmpty(videoResource.Episode))
                                            {
                                                msg += "第" + videoResource.Episode + "集";
                                            }
                                            if (!string.IsNullOrEmpty(videoResource.Language))
                                            {
                                                msg += videoResource.Language + "版";
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            msg = "播放";
                                        }
                                        player.Play(msg);
                                        RegisterTencentVedioInstallState(player.IsInstalled);
                                        if (!player.IsInstalled)
                                        {
                                            playControlResponseData.ResponseText = "你没有安装腾讯视频客户端，如果从此链接获取，将可以通过语音点播腾讯视频里的内容";
                                            playControlResponseData.TTSUrl = XiaoweiAI.Instance.RequestTTS("你没有安装腾讯视频客户端，如果从此链接获取，将可以通过语音点播腾讯视频里的内容");
                                            playControlBubbleViewModel.ShowNoVideoTip = true;
                                            playControlBubbleViewModel.ShowResponse = false;
                                        }
                                    }
                                    break;
                                case PlayerType.News:
                                case PlayerType.Radio:
                                case PlayerType.Weixintingshu:
                                    if (playControlResponseData.PlayableResource is IRadioResource radioResource)
                                    {
                                        PlayerManager.Instance.CurrentPlayer = player;
                                        QQFMList qqFMList = new QQFMList();
                                        //penguinFMList.Collection.Add
                                        if (radioResource.RadioItemList.Count == 0) break;
                                        string radioCover = "";
                                        qqFMList.HasMareDown = radioResource.HasMorePlayResource;
                                        qqFMList.RequestGetMoreDown += QQFMList_RequestGetMoreDown;
                                        qqFMList.HasMoreUp = radioResource.HasMorePlayResourceUp;
                                        qqFMList.RequestGetMoreUp += QQFMList_RequestGetMoreUp;
                                        qqFMList.RequestRefreshURL += QQFMList_RequestRefreshURL;
                                        qqFMList.Skill = (XiaoweiV2.Skill)playControlResponseData.PlayStateAdditionalMessage;
                                        PlayerService.Instance.Skill = qqFMList.Skill;
                                        foreach (var info in radioResource.RadioItemList)
                                        {
                                            if (!String.IsNullOrEmpty(info.CoverUrl))
                                            {
                                                radioCover = info.CoverUrl;
                                            }
                                            // check the url


                                            QQFMItem qqFMItem;
                                            qqFMItem = new QQFMItem()
                                            {
                                                Source = info.Source,
                                                Title = info.Title,
                                                MediaUri = info.MediaUri,
                                                CoverUrl = string.IsNullOrEmpty(radioCover)? "ms-appx:///Assets/Player/play-list.png" : radioCover,
                                                Summary = info.Summary,
                                                PlayId = info.PlayId,
                                                IsCurrent = false,
                                                IsNews = playControlResponseData.PlayerType == PlayerType.News
                                            };

                                            qqFMList.Collection.Add(qqFMItem);
                                        }

                                        qqFMList.CurrentItem = qqFMList.Collection[0];
                                        Debug.WriteLine($"RadioModel.PlayBehavior:{radioResource.PlaylistAction}");
                                        switch (radioResource.PlaylistAction)
                                        {
                                            case PlaylistAction.ReplaceAll:
                                                player.Play(qqFMList);
                                                break;
                                            case PlaylistAction.EnqueueFront:
                                                XiaoweiPlayerManager.Instance.OperateList(qqFMList, ListOperation.EnqueueFront);
                                                break;
                                            case PlaylistAction.EnqueueBack:
                                                XiaoweiPlayerManager.Instance.OperateList(qqFMList, ListOperation.EnqueueBack);
                                                break;
                                            case PlaylistAction.ReplaceEnqueue:
                                                break;
                                            case PlaylistAction.RefreshURL:
                                                XiaoweiPlayerManager.Instance.OperateList(qqFMList, ListOperation.RefreshUrl);
                                                break;
                                            case PlaylistAction.Remove:
                                                break;
                                            default:
                                                break;
                                        }
                                    break;
                                    }
                                    break;
                            }
                            break;
                        case PlayControlType.Unknow:
                            break;
                        default:
                            break;
                    }
                }
            }
            if (string.IsNullOrEmpty(responseData.ResponseText))
            {
                responseData.TTSUrl = "";
            }
            DefaultResponseHandler.Handle(responseData);
        }

        private static void QQFMList_RequestRefreshURL(string skillID, string playID)
        {
            if (skillID != Skills.WeixinTingShu)
            {
                return;
            }
            XiaoweiAI.Instance.GetResourceURL(new string[] { playID });
        }

        private static void QQFMList_RequestGetMoreUp(object sender, object e)
        {
            if (e is QQFMList.GetMoreArgs args)
            {
                XiaoweiAI.Instance.GetMoreResources(args.skill, args.PlayID, true);
            }
        }

        private static void QQFMList_RequestGetMoreDown(object sender, object e)
        {
            if (e is QQFMList.GetMoreArgs args)
            {
                XiaoweiAI.Instance.GetMoreResources(args.skill, args.PlayID, false);
            }
        }

        public static void RegisterTencentVedioInstallState(bool newState)
        {
            int state = LocalSettings.TencentVedioInstallState;
            if (!newState)
            {
                if (state == 2)
                {
                    LocalSettings.TencentVedioInstallState = 0;
                }
            }
            else
            {
                if (state == 1)
                {
                    Task<bool>.Run(async () => { return await Helpers.ServerApi.Instance.DownloadRecord(Helpers.ServerApi.SupportedApp.TecentVideo.GetHashCode(), XiaoweiAI.Instance.UserId, LocalSettings.DeviceName); }).Wait();
                }
                LocalSettings.TencentVedioInstallState = 2;
            }

        }
    }
}
